package com.techwells.applicationMarket.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

/**
 * java后台极光推送方式二：使用Java SDK
 */

public class Jpush {
	private static final Logger log = LoggerFactory.getLogger(Jpush.class);
	private static String masterSecret = "453e9999ba1f102d66cdbb84";
	private static String appKey = "d87f22041837b01a1b2788ee";

	// private static final String ALERT = "推送信息";
	/**
	 * 极光推送
	 * 
	 * @param alias
	 *            针对别名（接收推送的对象）
	 * @param alert
	 *            推送的内容
	 * @param messageType
	 */
	public static void jiguangPush(String alias, String alert, int messageType) {
		log.info("对别名" + alias + "的用户推送信息");
		PushResult result = push(alias, alert, messageType);
		if (result != null && result.isResultOK()) {
			log.info("针对别名" + alias + "的信息推送成功！");
		} else {
			log.info("针对别名" + alias + "的信息推送失败！");
		}
	}

	/**
	 * 生成极光推送对象PushPayload（采用java SDK）
	 * @param alias
	 * @param alert
	 * @return PushPayload
	 */
	public static PushPayload buildPushObject_android_ios_alias_alert(
			String alias, String alert, int messageType) {
		return PushPayload
				.newBuilder()
				.setPlatform(Platform.android_ios())
				.setAudience(Audience.alias(alias))
				.setNotification(
						Notification
								.newBuilder()
								.addPlatformNotification(
										AndroidNotification
												.newBuilder()
												.addExtra("messageType",
														messageType)
												.setAlert(alert).build())
								.addPlatformNotification(
										IosNotification
												.newBuilder()
												.addExtra("messageType",
														messageType)
												.setAlert(alert).build())
								.build())
				.setOptions(Options.newBuilder().setApnsProduction(true)// true-推送生产环境
																		// false-推送开发环境（测试使用参数）
						.setTimeToLive(90)// 消息在JPush服务器的失效时间（测试使用参数）
						.build()).build();
	}

	/**
	 * 极光推送方法(采用java SDK)
	 * @param alias
	 * @param alert
	 * @return PushResult
	 */
	public static PushResult push(String alias, String alert, int messageType) {
		ClientConfig clientConfig = ClientConfig.getInstance();
		JPushClient jpushClient = new JPushClient(masterSecret, appKey, null,
				clientConfig);
		PushPayload payload = buildPushObject_android_ios_alias_alert(alias,
				alert, messageType);
		try {
			return jpushClient.sendPush(payload);
		} catch (APIConnectionException e) {
			log.error("Connection error. Should retry later. ", e);
			return null;
		} catch (APIRequestException e) {
			log.error(
					"Error response from JPush server. Should review and fix it. ",
					e);
			log.info("HTTP Status: " + e.getStatus());
			log.info("Error Code: " + e.getErrorCode());
			log.info("Error Message: " + e.getErrorMessage());
			log.info("Msg ID: " + e.getMsgId());
			return null;
		}
	}

	/**
	 * 针对别名的消息推送
	 * 
	 */

	public static void pushMessage(String registrationId, String alert,
			int messageType) {

		JPushClient jpushClient = new JPushClient(masterSecret, appKey, null,
				ClientConfig.getInstance());

		PushPayload payload = buildPushObject_ios_tagAnd_alertWithExtrasAndMessage(
				registrationId, alert, messageType);

		try {
			PushResult result = jpushClient.sendPush(payload);
			System.out.println(result.msg_id);
			System.out.println(result);

		} catch (APIConnectionException e) {
		} catch (APIRequestException e) {
		}
	}

	public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage(
			String registrationId, String alert, int messageType) {
		return PushPayload
				.newBuilder()
				.setPlatform(Platform.android_ios())
				.setAudience(Audience.registrationId(registrationId))
				.setNotification(
						Notification
								.newBuilder()
								.addPlatformNotification(
										IosNotification
												.newBuilder()
												.setAlert(alert)
												.setSound("happy")
												.addExtra("messageType",
														messageType)
												.addExtra("type", "我是问题")
												.build()).build())
				.setMessage(Message.content(alert))
				.setOptions(
						Options.newBuilder().setApnsProduction(true).build())
				.build();
	}

	public static void jiguangPush1(String[] alias, String alert,
			int messageType) {
		// String alias = "123456";//声明别名
		log.info("对别名" + alias + "的用户推送信息");
		PushResult result = push1(alias, alert, messageType);
		if (result != null && result.isResultOK()) {
			log.info("针对别名" + alias + "的信息推送成功！");
		} else {
			log.info("针对别名" + alias + "的信息推送失败！");
		}
	}

	public static PushPayload buildPushObject_android_ios_alias_alert1(
			String[] alias, String alert, int messageType) {
		return PushPayload
				.newBuilder()
				.setPlatform(Platform.android_ios())
				.setAudience(Audience.alias(alias))
				.setNotification(
						Notification
								.newBuilder()
								.addPlatformNotification(
										AndroidNotification
												.newBuilder()
												.addExtra("messageType",
														messageType)
												.setAlert(alert).build())
								.addPlatformNotification(
										IosNotification
												.newBuilder()
												.addExtra("messageType",
														messageType)
												.setAlert(alert).build())
								.build())
				.setOptions(Options.newBuilder().setApnsProduction(false)// true-推送生产环境
																		// false-推送开发环境（测试使用参数）
						.setTimeToLive(90)// 消息在JPush服务器的失效时间（测试使用参数）
						.build()).build();
	}

	/**
	 * 极光推送方法(采用java SDK)
	 * 
	 * @param alias
	 * @param alert
	 * @return PushResult
	 */
	public static PushResult push1(String[] alias, String alert, int messageType) {
		ClientConfig clientConfig = ClientConfig.getInstance();
		JPushClient jpushClient = new JPushClient(masterSecret, appKey, null,
				clientConfig);
		PushPayload payload = buildPushObject_android_ios_alias_alert1(alias,
				alert, messageType);
		try {
			return jpushClient.sendPush(payload);
		} catch (APIConnectionException e) {
			log.error("Connection error. Should retry later. ", e);
			return null;
		} catch (APIRequestException e) {
			log.error(
					"Error response from JPush server. Should review and fix it. ",
					e);
			log.info("HTTP Status: " + e.getStatus());
			log.info("Error Code: " + e.getErrorCode());
			log.info("Error Message: " + e.getErrorMessage());
			log.info("Msg ID: " + e.getMsgId());
			return null;
		}
	}

	/**
	 * @description 按别名推送投透传消息
	 */
	public static void pushMessage1(String alias, String alert, int messageType) {

		JPushClient jpushClient = new JPushClient(masterSecret, appKey, null,
				ClientConfig.getInstance());

		PushPayload payload = buildPushObject_ios_tagAnd_alertWithExtrasAndMessage1(
				alias, alert, messageType);

		try {
			PushResult result = jpushClient.sendPush(payload);
			System.out.println(result.msg_id);
			System.out.println(result);

		} catch (APIConnectionException e) {
		} catch (APIRequestException e) {
		}
	}

	public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage1(
			String alias, String alert, int messageType) {
		return PushPayload
				.newBuilder()
				.setPlatform(Platform.android_ios())
				.setAudience(Audience.alias(alias))
				.setNotification(
						Notification
								.newBuilder()
								.addPlatformNotification(
										IosNotification
												.newBuilder()
												.setAlert(alert)
												.setSound("happy")
												.addExtra("messageType",
														messageType).build())
								.build())
				.setMessage(Message.content(alert))
				.setOptions(
						Options.newBuilder().setApnsProduction(true).build())
				.build();
	}

	public static void main(String[] args) {
		Jpush.jiguangPush("7", "我来测试推送速度00000", 9999);
		// Jdpush.pushMessage("191e35f7e04e6fe4736", "我来踢人了", 99);
		// Jdpush.pushMessage1("1", "THANKS_123", 66);
	}
}
